<template>
	<nut-dialog
		title="需完善信息,并为您开通PC后台"
		:close-on-click-overlay="false"
		v-model:visible="phoneNumberFlag"
	>
		<template v-slot:default>
			<div class="nut-dialog-form-item-z">
				<div class="form-item-title">手机号</div>
				<nut-input
					v-model="basicData.phoneNumber"
					class="nut-input-text-input"
					placeholder="请输入手机号"
					type="text"
				/>
			</div>
			<div class="nut-dialog-form-item-z">
				<div class="form-item-title">密码</div>
				<nut-input
					v-model="basicData.password"
					class="nut-input-text-input"
					placeholder="请输入密码"
					:type="passwordVisible1 ? 'text' : 'password'"
				/>
				<div
					class="icon-hidden-show"
					v-if="basicData.password"
				>
					<IconFont
						name="eye"
						size="10"
						v-if="passwordVisible1"
						@click="passwordVisible1 = !passwordVisible1"
					></IconFont>
					<IconFont
						size="10"
						name="marshalling"
						v-else
						@click="passwordVisible1 = !passwordVisible1"
					></IconFont>
				</div>
			</div>
			<div class="nut-dialog-form-item-z">
				<div class="form-item-title">确认密码</div>
				<nut-input
					v-model="basicData.confirmPassword"
					class="nut-input-text-input"
					placeholder="请再次输入密码"
					:type="passwordVisible2 ? 'text' : 'password'"
				/>

				<div
					class="icon-hidden-show"
					v-if="basicData.confirmPassword"
				>
					<IconFont
						name="eye"
						size="10"
						v-if="passwordVisible2"
						@click="passwordVisible2 = !passwordVisible2"
					></IconFont>
					<IconFont
						size="10"
						name="marshalling"
						v-else
						@click="passwordVisible2 = !passwordVisible2"
					></IconFont>
				</div>
			</div>
			<div class="nut-dialog-form-item-z-yzm nut-dialog-form-item-z">
				<div class="form-item-title">验证码</div>
				<nut-input
					v-model="basicData.yzCode"
					class="nut-input-text-input"
					placeholder="请输入验证码"
					type="text"
				/>

				<div class="btn">
					<nut-button
						v-if="!yzData.countDownIng"
						size="mini"
						color="linear-gradient(to right, #5232B7,#7237BC)"
						@click="getCodeYZM"
						style="font-size: 8px"
						type="danger"
						>获取验证码</nut-button
					>
					<span
						style="color: #5232b7"
						v-if="yzData.countDownIng"
						>{{ yzData.countDownTime }}s</span
					>
				</div>
			</div>
		</template>

		<template v-slot:footer>
			<nut-row :gutter="10">
				<nut-col :span="12">
					<div class="flex-content">
						<nut-button
							type="default"
							block
							>取消</nut-button
						>
					</div>
				</nut-col>
				<nut-col :span="12">
					<div class="flex-content flex-content-light">
						<nut-button
							:disabled="!formatPhoneInput()"
							block
							color="linear-gradient(to right, #5232B7,#7237BC)"
							@click="onConfirmPhone"
							>确定</nut-button
						>
					</div>
				</nut-col>
			</nut-row>
		</template>
	</nut-dialog>

	<nut-dialog
		no-cancel-btn
		title="账号无权限,请联系运营开通权限"
		text-align="left"
		:close-on-click-overlay="false"
		:content="`&nbsp;&nbsp&nbsp;&nbsp&nbsp;&nbsp;&nbsp;注册账号:&nbsp;&nbsp;${
			Userinfo?.userName
		}\n\n&nbsp;&nbsp&nbsp;&nbsp&nbsp;&nbsp;&nbsp;注册时间:&nbsp;&nbsp;${formatShowTime(
			Userinfo?.regTime
		)}`"
		v-model:visible="visible3"
	>
		<template v-slot:footer>
			<div class="flex-content flex-content-light">
				<nut-button
					block
					color="linear-gradient(to right, #5232B7,#7237BC)"
					@click="onOk"
					>确定</nut-button
				>
			</div>
		</template>
	</nut-dialog>
	<div class="index-container">
		<Header
			@onHeaderBySearch="getSearchValue"
			@onHeaderByClear="searchClear"
			:listType="listType"
		></Header>

		<div class="ocr-container">
			<div class="ocr-box">
				<div class="identify-box">
					<div class="left">
						<div class="icon">
							<IconFont
								size="23"
								name="http://h5.liangpiao.net.cn/logo/dianying.png"
							></IconFont>
						</div>
						<div class="characters-box">
							<text class="txt">识别下单</text>
						</div>
					</div>

					<div class="center"></div>

					<div
						@click="dianWen"
						class="right"
					>
						<div class="right-desc">
							<text style="font-size: 13px">上传照片 一键下单</text>
						</div>

						<div class="ask">?</div>
					</div>
				</div>

				<div class="identify-btn">
					<div class="input-box">
						<input
							type="file"
							accept="image/png,image/jpeg,image/gif"
							@change="handleFileChange($event)"
						/>
					</div>

					<nut-button
						size="small"
						color="#5232b7"
						>立即上传</nut-button
					>
				</div>
			</div>
		</div>

		<Filter
			:tabList="filterList"
			@onChange="getTabs"
			:listType="listType"
			v-if="filterFlag"
		></Filter>

		<SearchFilter
			@onRegionChanged="onRegionChanged"
			@onBrandChanged="onBrandChanged"
			v-if="listType"
		></SearchFilter>

		<div
			class="flex-container"
			:style="{ height: `${listContainerHeight - tabbarHeight}px` }"
			v-if="isShowList"
		>
			<template v-if="listContainerHeight && listContainerHeight > 0">
				<scroll-view
					:scroll-y="true"
					:style="{ height: `${listContainerHeight - tabbarHeight}px` }"
					scrollAnchoring
					@scrolltolower="onScrollBottom"
					:scroll-top="scrollTop"
				>
					<!-- :scroll-top="scrollTop" -->
					<div
						class="flex-item1"
						v-if="listType"
						v-for="(items, index) in cinemaList"
						:key="index"
					>
						<CameraItem
							:info="items"
							@click="handleCinemaItem(items)"
						></CameraItem>
					</div>
					<div
						class="flex-item"
						v-else
						v-for="(item, indexs) in movieList"
						:key="indexs"
					>
						<MovieItem
							:info="item"
							@click="handleMovieItem(item)"
						></MovieItem>
					</div>
					<!-- <div style="height: 10px;" v-if="listType"></div> -->
					<!-- 影院列表的空状态 -->
					<nut-empty
						v-if="cinemaList.length === 0 && listType"
						description="无数据"
					></nut-empty>
					<template v-if="!isShowList">
						<nut-skeleton
							:style="{ width: '100%', margin: '0.5rem 0.5rem' }"
							width="100%"
							height="15px"
							title
							animated
							row="3"
						>
						</nut-skeleton>
						<nut-skeleton
							:style="{ width: '100%', margin: '0.5rem 0.5rem' }"
							width="100%"
							height="15px"
							title
							animated
							row="3"
						>
						</nut-skeleton>
						<nut-skeleton
							:style="{ width: '100%', margin: '0.5rem 0.5rem' }"
							width="100%"
							height="15px"
							title
							animated
							row="3"
						>
						</nut-skeleton>
						<nut-skeleton
							:style="{ width: '100%', margin: '0.5rem 0.5rem' }"
							width="100%"
							height="15px"
							title
							animated
							row="3"
						>
						</nut-skeleton>
						<nut-skeleton
							:style="{ width: '100%', margin: '0.5rem 0.5rem' }"
							width="100%"
							height="15px"
							title
							animated
							row="3"
						>
						</nut-skeleton>
						<nut-skeleton
							:style="{ width: '100%', margin: '0.5rem 0.5rem' }"
							width="100%"
							height="15px"
							title
							animated
							row="3"
						>
						</nut-skeleton>
						<nut-skeleton
							:style="{ width: '100%', margin: '0.5rem 0.5rem' }"
							width="100%"
							height="15px"
							title
							animated
							row="3"
						>
						</nut-skeleton>
					</template>
					<!-- 电影列表的空状态 -->
					<nut-empty
						v-if="movieList.length === 0 && !listType"
						description="无数据"
					></nut-empty>
					<Loading
						v-if="listType"
						:page="cinemaInfo.currentPage"
						:total="cinemaPageInfo.totalPage"
						:loadingFlag="loadingFlag"
						:tipFlag="tipFlag"
					></Loading>
					<div
						style="height: 50px"
						v-if="listType"
					></div>
				</scroll-view>
			</template>
			<ua-loading
				v-model="loadingstyle"
				background="rgba(0,0,0,.5)"
			>
				<template #spinner>
					<span class="custom-loading">
						<em></em><em></em><em></em><em></em><em></em>
					</span>
				</template>
				<template #text>
					<div style="color: #fff; font-size: 14px; font-weight: 700">
						Loading...
					</div>
				</template>
			</ua-loading>
		</div>

		<Tabbar></Tabbar>
	</div>

	<nut-popup
		v-model:visible="showTop"
		closeable
		round
		:close-on-click-overlay="false"
		safe-area-inset-bottom
		:style="{ minHeight: '100px', width: '85%' }"
	>
		<div class="identify-tip-box">
			<div class="box">
				<div class="displayFlex marginTop">
					<text class="tip">照片上传说明示例</text>
				</div>

				<div class="displayFlex row2">
					<div class="img">
						<image
							src="../../assets/images/1.jpg"
							style="width: 140px; height: 140px"
						></image>
					</div>

					<div class="right-box">
						<div class="desc-box">
							<text style="font-size: 19px; font-weight: bold">Step</text>

							<div style="padding-left: 10px">
								<text
									style="
										display: flex;
										align-items: center;
										justify-content: center;
										width: 30px;
										height: 30px;
										background-color: #593aba;
										color: #fff;
										border-radius: 50%;
										font-size: 18px;
									"
									>01</text
								>
							</div>
						</div>

						<div
							style="
								display: flex;
								flex-direction: row;
								flex-wrap: wrap;
								margin-top: 10px;
							"
						>
							<text style="font-size: 12.5px; color: #c6c1bd"
								>去淘票票/猫眼选择你想看的
								<text style="color: #593aba">电影场次座位然后截图。</text>
							</text>
						</div>
					</div>
				</div>

				<div
					class="displayFlex"
					style="
						width: 100%;
						margin-top: 30px;
						height: 150px;
						margin-top: 0px;
						z-index: 999;
					"
				>
					<div
						style="
							display: flex;
							flex-direction: column;
							width: 100%;
							height: 100%;
							margin-right: 20px;
						"
					>
						<div style="display: flex; flex-direction: row">
							<text style="font-size: 19px; font-weight: bold">Step</text>

							<div style="padding-left: 10px">
								<text
									style="
										display: flex;
										align-items: center;
										justify-content: center;
										width: 30px;
										height: 30px;
										background-color: #593aba;
										color: #fff;
										border-radius: 50%;
										font-size: 18px;
									"
									>02</text
								>
							</div>
						</div>

						<div
							style="
								display: flex;
								flex-direction: row;
								flex-wrap: wrap;
								margin-top: 10px;
							"
						>
							<text style="font-size: 12.5px; color: #c6c1bd"
								>把带有影院、影片、时间、座位的截图上传！
								<text style="color: #593aba">（截图照片如右图所示）</text>
							</text>
						</div>
					</div>

					<div>
						<image
							src="../../assets/images/2.jpg"
							style="width: 110px; height: 150px"
						></image>
					</div>
				</div>

				<div
					style="display: flex; justify-content: center; align-items: center"
				>
					<text style="color: #593aba; font-size: 15px"
						>注：请确认场次人数后付款</text
					>
				</div>

				<div style="width: 100%; margin: 15px 0px 10px 0">
					<div
						style="
							position: absolute;
							z-index: 999;
							width: 85%;
							height: 40px;
							opacity: 0;
						"
					>
						<input
							type="file"
							accept="image/png,image/jpeg,image/gif"
							@change="handleFileChange($event)"
						/>
					</div>

					<nut-button
						style="
							background-color: #5232b7;
							color: #fff;
							width: 100%;
							height: 40px;
							font-size: 16px;
						"
						size="small"
						>立即上传</nut-button
					>
				</div>
			</div>
		</div>
	</nut-popup>

	<nut-popup
		v-model:visible="showTopXian"
		closeable
		round
		:close-on-click-overlay="false"
		safe-area-inset-bottom
		:style="{ minHeight: '100px', width: '85%' }"
	>
		<XianQin
			:dataShu="dataShu"
			ref="XianQinRef"
			@onClose="getClose"
		></XianQin>
	</nut-popup>
</template>

<script setup lang="ts">
import {
	reactive,
	toRefs,
	nextTick,
	ref,
	onMounted,
	computed,
	watch,
} from "vue";
import { storeToRefs } from "pinia";
import { useTabbarStore } from "../../store";
import { useUserStore } from "../../store";
import { useLocationStore } from "../../store";
import { IconFont } from "@nutui/icons-vue-taro";
import Loading from "../../component/Loading/index";
import SearchFilter from "../../component/cinema-search-filter";
import moment from "moment";

import * as homeApi from "../../api/cinema";
import Header from "./component/header/index";
import CameraItem from "./component/item/index";
import Taro, { useDidShow } from "@tarojs/taro";
import Tabbar from "../../component/Tabbar";
import Filter from "./component/filter/filter.vue";
import uaLoading from "../../component/ua-loading/ua-loading.vue";
import MovieItem from "./component/movie-item/index";
import * as loginApi from "../../api/loginApi";
import wx from "../../../node_modules/weixin-js-sdk/index";
import XianQin from "./common/index.vue";
import { upload } from "../../utils/oss";
import { getRandom } from "../../utils/validate";
import * as cinemaApi from "../../api/cinema";

const router = Taro.useRouter();
const phoneNumberFlag = ref(false);
const tabbarStore = useTabbarStore();
const userStore = useUserStore();
const { selected, tabbarHeight } = storeToRefs(tabbarStore);
const { Userinfo } = storeToRefs(userStore);
const locationStore = useLocationStore();
const { getSelectCityinfo, getCitylatlng } = storeToRefs(locationStore);

const showTop = ref(false); // 弹出层
const showTopXian = ref(false); // 影票识别详情

const basicData = reactive({
	phoneNumber: "",
	password: "",
	confirmPassword: "",
	yzCode: "",
});
const visible3 = ref(false);
const loadingFlag = ref(false); //加载loding
const tipFlag = ref(false); //加载提示
const listType = ref(0); //列表类型
const filterFlag = ref(false); //是否显示过滤
const isShowList = ref(true); //是否显示 列表
const movieInfo = ref({
	cityId: getSelectCityinfo.value.id,
	filmName: "",
}); //电影列表参数

//验证码数据
const yzData = reactive({
	formData: {
		phone: "",
		code: "",
	},
	// 倒计时
	countDownTime: 60,
	timer: null,
	countDownIng: false,
});
const scrollTop = ref(0);
const loadingstyle = ref(false);
const passwordVisible1 = ref(false);
const passwordVisible2 = ref(false);
const openid = ref("");
const appId = ref("wx105b45b9c2647d9b");
// const appId = ref("wxc6c1a2528ecc3e55") //测试环境

const dataShu = ref();
const XianQinRef = ref();

const userInfo = ref({});
const filterList = ref([
	{
		name: "电影",
		id: 0,
	},
	{
		name: "影院",
		id: 1,
	},
]);

// 监听选择城市变化
watch(
	() => locationStore.selectCityinfo,
	() => {
		cinemaInfo.value.currentPage = 1;
		cinemaInfo.value.areaId = locationStore.selectCityinfo.id;
		(cinemaInfo.value.cinemaLat = getCitylatlng.value[0]),
			(cinemaInfo.value.cinemaLng = getCitylatlng.value[1]);
		getList();
		getCinema(0);
	}
);

/** 点击问号 */
const dianWen = () => {
	showTop.value = true;
};

/** 关闭影票识别详情 */
const getClose = () => {
	showTopXian.value = false;
};

/** 上传图片 */
const handleFileChange = async (event) => {
	showTop.value = false;

	Taro.showLoading({ title: "加载中", mask: true });

	const file = event.target.childNodes[0].files[0];

	const res = (await readFile(file)) as any;

	const alRes = await upload(res.ossBuffer, file, "replyAnswerImg");

	beforeXhrUpload(alRes.url);
};

/** 识别图片 */
const beforeXhrUpload = (val: string) => {
	Taro.request({
		url: `http://manage-api.liangpiao.net.cn/verify/addIdentifyTask`,
		// url: `    http://k8s-cluster.liangpiaovip.com:30080/liangpiao-consume/verify/addIdentifyTask`,

		method: "POST",
		data: {
			outTaskId: getRandom(19),
			filePath: val,
		},
		header: {
			"content-type": "application/json", // 默认值
		},
		success: function (res) {
			if (res.data.state == 200) {
				var timesRun = 0;

				const toRun = 20; // 循环多少次

				var interval = setInterval(function () {
					duYing(res.data.data).then((val: any) => {
						if (timesRun >= toRun || val) {
							clearInterval(interval);

							Taro.hideLoading();
							if (timesRun >= toRun || val.errorMsg) {
								Taro.showToast({
									title: val.errorMsg || "图片识别失败，请稍后重试~",
									duration: 3000,
									icon: "none",
								});

								return;
							} else {
								dataShu.value = val;

								Taro.setStorageSync("yinTu", {
									image: val?.identifyTaskVo.filmImg,
									showId: val?.identifyTaskVo.discern.showId,
								});

								getHuoQu(val?.identifyTaskVo.discern.showId);
							}

							return;
						}

						timesRun += 1;
					});
				}, 3000);
			}
		},
		fail: function () {
			// beforeXhrUpload(val);
		},
	});
};

const duYing = async (val: any) => {
	let data = undefined;
	await Taro.request({
		url: `http://manage-api.liangpiao.net.cn/verify/identifyTaskResult/${val}`,
		// url: `http://k8s-cluster.liangpiaovip.com:30080/liangpiao-consume/verify/identifyTaskResult/${val}`,

		method: "GET",
		header: {
			"content-type": "application/json",
		},
		success: function (row) {
			if (row.data.result) {
				if (row.data.data.result == true || row.data.data.result == false) {
					data = row.data.data;
				}
			}
		},
		fail: function () {
			data = undefined;
		},
	});

	return data;
};

const getHuoQu = async (data: any) => {
	const res: any = await cinemaApi.seat({ showId: data });
	// console.log(res, 123)

	if (res.state == 200) {
		const a = {
			regions: res.data.regions,
			cinemaLineVo: res.data.cinemaLineVo,
			cinemaShow: res.data.cinemaShow,
		};
		console.log(a, "a");

		showTopXian.value = true;

		setTimeout(() => {
			XianQinRef.value.childMethod(a);

			$('input[type="file"]').val(null);
		}, 500);

		return;
	}
};

const readFile = (file) => {
	// console.log(file, "-------------");
	return new Promise((resolve, reject) => {
		const OSS = require("ali-oss");
		let fileRead = new FileReader() as any;
		fileRead.readAsDataURL(file);
		fileRead.onload = function (e) {
			const base64File = fileRead.result.replace(/^data:\w+\/\w+;base64,/, "");
			const ossBuffer = new OSS.Buffer(base64File, "base64");
			resolve({ ossBuffer, fileRead });
		};
	});
};

const formatShowTime = computed(() => {
	return (str) => {
		var formattedTime = moment.unix(str / 1000).format("YYYY-MM-DD HH:mm:ss");
		return formattedTime;
	};
}); // 【格式化】散场时间
//搜索关键词
const getSearchValue = (e) => {
	if (listType.value) {
		cinemaInfo.value.currentPage = 1;
		cinemaInfo.value.pageSize = 999;
		(cinemaInfo.value.cinemaLat = getCitylatlng.value[0]),
			(cinemaInfo.value.cinemaLng = getCitylatlng.value[1]);

		cinemaInfo.value.cinemaName = e;
		getCinema(0);
	} else {
		movieInfo.value.filmName = e;
		getList();
	}
};
//搜素框删除
const searchClear = () => {
	if (listType.value) {
		delete cinemaInfo.value.cinemaName;
		(cinemaInfo.value.cinemaLat = getCitylatlng.value[0]),
			(cinemaInfo.value.cinemaLng = getCitylatlng.value[1]);
		cinemaInfo.value.currentPage = 1;
		cinemaInfo.value.pageSize = 10;
		getCinema(0);
	} else {
		movieInfo.value.filmName = "";
		getList();
	}
};
const movieList = ref([]);
const cinemaList = ref([]);
const cinemaInfo = ref({
	currentPage: 1,
	pageSize: 10,
	areaId: 0,
	cinemaLat: getCitylatlng.value[0],
	cinemaLng: getCitylatlng.value[1],
	cinemaLineId: 0,
});
const cinemaPageInfo = ref({
	total: 0,
	totalPage: 0,
});
const timer = ref(null);
//tabs 切换
const getTabs = (val) => {
	isShowList.value = false;
	listType.value = val.id;
	scrollTop.value = 0;

	if (val.id) {
		cinemaInfo.value.currentPage = 1;
		(cinemaInfo.value.cinemaLat = getCitylatlng.value[0]),
			(cinemaInfo.value.cinemaLng = getCitylatlng.value[1]);
		getCinema(0);
	} else {
		getList();
	}
};

//分页节流
const throttle = (func, delay) => {
	let lastTime = 0;
	return function () {
		const now = new Date().getTime();
		if (now - lastTime >= delay) {
			func.apply(this, arguments);
			lastTime = now;
		}
	};
};
// //滚动分页处理函数 status 状态 1:分页 0:筛选
// const onScrollBottom = (e) => {
//   // console.log(e);

//   if (!listType.value) {
//     return

//   }
//   loadingFlag.value = true
//   if (timer.value) {
//     clearTimeout(timer.value);
//   }
//   timer.value = setTimeout(() => {
//     console.log(cinemaInfo.value.currentPage, cinemaPageInfo.value.totalPage);
//     tipFlag.value = false

//     if (cinemaInfo.value.currentPage < cinemaPageInfo.value.totalPage) {
//       cinemaInfo.value.currentPage++;
//       getCinema(1)
//     } else {
//       // Taro.showToast({
//       //   title: "没有更多数据了呢",
//       //   icon: "none",
//       // });
//       loadingFlag.value = false
//       tipFlag.value = true
//     }
//   }, 1000);

// };

const onScrollBottom = throttle(() => {
	if (!listType.value) {
		return;
	}
	loadingFlag.value = true;
	tipFlag.value = false;

	console.log(cinemaInfo.value.currentPage, cinemaPageInfo.value.totalPage);
	tipFlag.value = false;

	if (cinemaInfo.value.currentPage < cinemaPageInfo.value.totalPage) {
		cinemaInfo.value.currentPage++;
		getCinema(1);
	} else {
		loadingFlag.value = false;
		tipFlag.value = true;
	}
}, 1000);

// 在绑定滚动事件时使用 onScrollBottom
window.addEventListener("scroll", onScrollBottom);
//区县
const onRegionChanged = (value) => {
	scrollTop.value = 0;
	isShowList.value = false;
	if (value === 0) {
		cinemaInfo.value.areaId = getSelectCityinfo.value.id;
	} else {
		cinemaInfo.value.areaId = value;
	}
	cinemaInfo.value.currentPage = 1;
	(cinemaInfo.value.cinemaLat = getCitylatlng.value[0]),
		(cinemaInfo.value.cinemaLng = getCitylatlng.value[1]);
	getCinema(0);
};
const onBrandChanged = (value) => {
	cinemaInfo.value.cinemaLineId = value;
	cinemaInfo.value.currentPage = 1;

	getCinema(0);
};

const handleMovieItem = (item) => {
	Taro.navigateTo({
		url: `/pages/movie-detail/index?filmId=${item.id}`,
	});
};
const handleCinemaItem = (item) => {
	// return
	Taro.navigateTo({
		url: `/pages/cinema-detail/index?cinemaId=${item.id}&cinemaCode=${item.cinemaCode}`,
	});
};

//注册确定
const onConfirmPhone = async () => {
	// return
	if (!basicData.phoneNumber) {
		Taro.showToast({
			title: "手机号不能为空",
			icon: "error",
		});
		return;
	}

	if (!basicData.password) {
		Taro.showToast({
			title: "请输入密码",
			icon: "error",
		});
		return;
	}
	if (!basicData.password) {
		Taro.showToast({
			title: "请输入密码",
			icon: "error",
		});
		return;
	}

	if (basicData.password !== basicData.confirmPassword) {
		Taro.showToast({
			title: "两次输入密码不一致",
			icon: "error",
		});
		return;
	}
	if (!basicData.yzCode) {
		Taro.showToast({
			title: "验证码不能为空",
			icon: "error",
		});
		return;
	}
	// Taro.setStorageSync("phoneNumber", phoneValue);
	let data = {
		userName: basicData.phoneNumber,
		userPassword: basicData.password,
		confirmPassword: basicData.confirmPassword,
		smsCode: basicData.yzCode,
		// userType: "Supply",
		openid: Taro.getStorageSync("openid"),
	};

	const res: any = await loginApi.userRegister(data);

	if (res.state == 200) {
		Taro.showToast({
			title: "注册成功",
		});
		phoneNumberFlag.value = false;
		loadingstyle.value = false;

		localStorage.removeItem("startTimeLogin");
		clearInterval(yzData.timer);
		yzData.countDownTime = 60;
		yzData.countDownIng = false;

		var openidStorage = Taro.getStorageSync("openid");
		if (openidStorage) {
			openid.value = openidStorage;
			const UserInfoRes = await loginApi
				.Login({ userName: openidStorage })
				.then((res: any) => res);
			if (UserInfoRes.state === 200) {
				Taro.setStorageSync("userInfo", UserInfoRes.data);
				userInfo.value = UserInfoRes.data;
				userStore.setUserinfo(UserInfoRes.data);
				userStore.setToken(UserInfoRes["token"]);
				loadingstyle.value = false;
				phoneNumberFlag.value = false;
				if (UserInfoRes.data.userBusinesses) {
					const hasFilmBusiness = UserInfoRes.data.userBusinesses.some(
						(item) => item.businessType === "Film"
					);
					if (!hasFilmBusiness) {
						setTimeout(() => {
							visible3.value = true;
						}, 500);
					}
				}
			} else if (UserInfoRes.state === 202) {
				phoneNumberFlag.value = false;

				Taro.showToast({
					icon: "none",
					title: UserInfoRes.message,
					duration: 3000,
				});

				// Taro.hideLoading();
				loadingstyle.value = false;
				setTimeout(() => {
					// wx.closeWindow()
				}, 200);

				// return
			} else {
			}
		} else {
			getCode();
		}
	} else {
		Taro.showToast({
			title: res.message,
			icon: "error",
		});
	}
};

const listContainerHeight = ref(0);
const getListContainerHeight = () => {
	const query = Taro.createSelectorQuery()
		.select(".flex-container")
		.boundingClientRect();
	query.selectViewport();
	query.exec(function (res) {
		if (res[0]) {
			listContainerHeight.value = res[0].height;
		}
	});
};
const getList = async () => {
	cinemaInfo.value.areaId = locationStore.selectCityinfo.id;
	movieList.value = [];
	for (const key in movieInfo.value) {
		if (
			movieInfo.value[key] === 0 ||
			movieInfo.value[key] === "" ||
			movieInfo.value[key] === null
		) {
			delete movieInfo.value[key];
		}
	}
	const result: any = await homeApi.listByMovie(movieInfo.value);
	if (result.state == 200) {
		movieList.value = result.data;
	}
	isShowList.value = true;
};

const getCinema = async (status) => {
	for (const key in cinemaInfo.value) {
		if (
			cinemaInfo.value[key] === 0 ||
			cinemaInfo.value[key] === "" ||
			cinemaInfo.value[key] === null
		) {
			delete cinemaInfo.value[key];
		}
	}
	const result: any = await homeApi.list(cinemaInfo.value);
	if (result.state == 200) {
		if (status) {
			if (result.data.cinemaListVo) {
				cinemaList.value = [
					...cinemaList.value,
					...result.data.cinemaListVo.list,
				];
				cinemaPageInfo.value.total = result.data.cinemaListVo.totalCount;
				cinemaPageInfo.value.totalPage = result.data.cinemaListVo.pageCount;
				loadingFlag.value = false;
			}
		} else {
			cinemaList.value = [];
			if (result.data.cinemaListVo) {
				cinemaList.value = result.data.cinemaListVo.list;
				cinemaPageInfo.value.total = result.data.cinemaListVo.totalCount;
				cinemaPageInfo.value.totalPage = result.data.cinemaListVo.pageCount;
			} else {
				cinemaList.value = [];
				cinemaPageInfo.value.total = 0;
				cinemaPageInfo.value.totalPage = 0;
			}
		}
		loadingFlag.value = false;
	} else if (result.state == 202 && result.message == "暂无影院信息") {
		if (status) {
			cinemaList.value = [...cinemaList.value, ...[]];
		} else {
			cinemaList.value = [];
		}
		loadingFlag.value = false;
	}
	isShowList.value = true;
};
// 校验手机号
const getCodeYZM = async () => {
	if (!basicData.phoneNumber || !basicData.password) {
		Taro.showToast({
			title: "请输入手机号和密码",
			icon: "error",
		});

		return;
	}
	countDown();
	const res: any = await loginApi.getYzm({
		userName: basicData.phoneNumber,
		// userType: 3,
	});
	if (res.code == 200) {
	}
};
//获取验证码倒计时
const countDown = () => {
	let startTime = localStorage.getItem("startTimeLogin");
	let nowTime = new Date().getTime();
	if (startTime) {
		let surplus = 60 - parseInt((nowTime - startTime) / 1000, 10);
		yzData.countDownTime = surplus <= 0 ? 0 : surplus;
	} else {
		yzData.countDownTime = 60;
		localStorage.setItem("startTimeLogin", nowTime);
	}

	yzData.timer = setInterval(() => {
		yzData.countDownTime--;
		yzData.getCodeDisabled = true;
		yzData.countDownIng = true;
		if (yzData.countDownTime <= 0) {
			localStorage.removeItem("startTimeLogin");
			clearInterval(yzData.timer);
			yzData.countDownTime = 60;
			yzData.countDownIng = false;
		}
	}, 1000);
};
//验证手机号格式
const formatPhoneInput = computed(() => {
	return () => {
		const re = /^1[3,4,5,6,7,8,9][0-9]{9}$/;
		const result = re.test(basicData.phoneNumber);
		if (!result) {
			return false;
		}
		return true;
	};
});

//用户重定向登录
const getUserInfo = async (option) => {
	// Taro.showLoading({
	//   title: "加载中...",
	//   mask: true,
	// });
	loadingstyle.value = true;

	let code = option.code;
	// console.log(Taro.getStorageSync("userInfo"));

	let userInfo = Taro.getStorageSync("userInfo")
		? Taro.getStorageSync("userInfo")
		: null;

	if (userInfo) {
		userInfo = await loginApi
			.userInfo({ userId: userInfo.id })
			.then((res: any) => res.data);
		if (!userInfo) {
			Taro.removeStorageSync("userInfo");
		}
	} else if (code) {
		const openId = await loginApi
			.EmitCodeByH5({ code })
			.then((res: any) => res.data);

		if (!openId) {
			// getCode()
		}
		openid.value = openId;
		Taro.setStorageSync("openid", openId);
		const UserInfoRes = await loginApi
			.Login({ userName: openId })
			.then((res: any) => res);
		if (UserInfoRes.state === 200) {
			phoneNumberFlag.value = false;
			userInfo = UserInfoRes.data;
			Taro.setStorageSync("userInfo", UserInfoRes.data);
			loadingstyle.value = false;
			userInfo.value = UserInfoRes.data;
			userStore.setUserinfo(UserInfoRes.data);
			userStore.setToken(UserInfoRes["token"]);
		} else if (
			UserInfoRes.state === 202 &&
			UserInfoRes.message === "请输入用户名"
		) {
			phoneNumberFlag.value = false;

			Taro.showToast({
				icon: "none",
				title: UserInfoRes.message,
				duration: 3000,
			});

			loadingstyle.value = false;
			return;
		} else if (
			UserInfoRes.state === 202 &&
			UserInfoRes.message === "系统错误"
		) {
			phoneNumberFlag.value = false;
			Taro.showToast({
				icon: "none",
				title: UserInfoRes.message,
				duration: 3000,
			});
			loadingstyle.value = false;
			return;
		} else if (
			UserInfoRes.state === 202 &&
			UserInfoRes.message === "没有找到该用户"
		) {
			phoneNumberFlag.value = true;
			loadingstyle.value = false;
			return;
		}
	}
	// 如果 userInfo 为空 代表 本地 没有 缓存数据 且 code 不存在 获取失效  重新获取code
	if (!userInfo) {
		getCode();
		return;
	} else {
		if (userInfo.userBusinesses) {
			const hasFilmBusiness = userInfo.userBusinesses.some(
				(item) => item.businessType === "Film"
			);
			if (!hasFilmBusiness) {
				visible3.value = true;
			}
		}
		if (userInfo.businessTypeList) {
			const hasFilmBusiness = userInfo.businessTypeList.some(
				(item) => item.businessType == 1
			);
			if (!hasFilmBusiness) {
				visible3.value = true;
			}
		}
		loadingstyle.value = false;
	}
};
const onOk = () => {
	setTimeout(() => {
		wx.closeWindow();
	}, 400);
};
const getCode = () => {
	// 网络重定向地址
	// let local = `http://liangpiao-v2-push-order-h5.liangpiao.net.cn/cdx2.html`; // 获取页面url
	let local = `http://h5.liangpiao.net.cn/cdx2.html`; // 获取页面url
	// let local=`http://businessh5-test-1323418546.cos-website.ap-shanghai.myqcloud.com/cdx2.html`

	// // // // 判断 如果是本地 开发 设置本地重定向地址
	// http://192.168.3.8:10086/

	// if (window.location.origin.indexOf("192.168.110.71") !== -1) {
	//   local = `http://h5.liangpiao.net.cn/cdx1.html`; // 获取页面url
	//   // local = `http://liangpiao-v2-push-order-h5.liangpiao.net.cn/cdx1.html`; // 获取页面url
	//   // local=`http://businessh5-test-1323418546.cos-website.ap-shanghai.myqcloud.com/cdx1.html`
	// }

	if (window.location.origin.indexOf("192.168.110.71") !== -1) {
		local = `http://h5.liangpiao.net.cn/cdx1.html`; // 获取页面url
		// local = `http://liangpiao-v2-push-order-h5.liangpiao.net.cn/cdx1.html`; // 获取页面url
		// local=`http://businessh5-test-1323418546.cos-website.ap-shanghai.myqcloud.com/cdx1.html`
	}

	//  地址转码
	local = encodeURIComponent(local);

	//  获取 code 地址
	let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId.value}&redirect_uri=${local}&response_type=code&connect_redirect=1&scope=snsapi_userinfo&state=STATE#wechat_redirect`;

	window.location.href = url;
	// Taro.hideLoading();
	loadingstyle.value = false;
};

onMounted(async () => {
	filterFlag.value = true;
	loadingstyle.value = true;
	tabbarStore.setSelected(0);
	await getListContainerHeight();
	getUserInfo(router.params);
	getList();
	// getCinema(0)
	let sendEndTime = localStorage.getItem("startTimeLogin");
	if (sendEndTime) {
		yzData.countDownIng = true;
		countDown();
	}
});
</script>

<style lang="scss">
.nut-uploader__slot {
	display: flex;
	width: 100%;
}

.fileInput {
	display: none;
}

.identify-tip-box {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	.box {
		width: 100%;
		margin: 20px 25px;
		display: flex;
		flex-direction: column;

		.displayFlex {
			display: flex;
			align-items: center;
			justify-content: center;
			.tip {
				font-weight: bold;
				font-size: 17px;
			}
		}
		.row2 {
			width: 100%;
			margin-top: 30px;
			height: 150px;
			.right-box {
				display: flex;
				flex-direction: column;
				width: 100%;
				height: 100%;
				margin-left: 20px;
			}
		}
		.marginTop {
			margin-top: 35px;
		}
	}
}

.ocr-container {
	width: 100%;
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	background-color: rgba(100, 53, 186, 0.1);
	.ocr-box {
		width: 100%;
		margin: 20px 20px;
		display: flex;
		align-items: center;
		flex-direction: row;
		justify-content: space-between;
		.identify-box {
			display: flex;
			align-items: center;
			.left {
				display: flex;
				align-items: center;
				flex-direction: row;
				height: 30px;
				.icon {
					display: flex;
					align-items: center;
					margin-right: 5px;
				}
				.characters-box {
					display: flex;
					align-items: flex-end;
					.txt {
						height: 100%;
						font-size: 32px;
						font-weight: bold;
						color: #5632b7;
					}
					.txt {
						height: 100%;
						font-size: 32px;
						font-weight: bold;
						color: #5632b7;
					}
				}
			}
			.center {
				display: flex;
				align-items: center;
				margin: 0px 8px;
				width: 1px;
				border-right: 1.5px solid #c6c1bd;
				height: 20px;
			}
			.right {
				display: flex;
				align-items: center;
				flex-direction: row;
				.right-desc {
					display: flex;
					align-items: center;
				}
				.ask {
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 50%;
					background-color: #5232b7;
					width: 25px;
					height: 25px;
					font-size: 17px;
					color: #fff;
					margin-left: 20px;
				}
			}
		}
		.identify-btn {
			display: flex;
			align-items: center;
			.input-box {
				position: absolute;
				z-index: 999;
				width: 91px;
				height: 32px;
				opacity: 0;
			}
		}
	}
}

.nut-dialog__header {
	height: 2rem;
	font-size: 28px;
}

.nut-dialog-form-item-z {
	display: flex;
	justify-content: space-between;
	align-items: center;
	position: relative;

	.form-item-title {
		flex: 2;
		text-align: left;
	}

	.nut-input-text-input {
		flex: 5;
		font-size: 22px !important;
	}

	.nut-input-text-input-1 {
		flex: 3;
	}

	.nut-input-text-input-2 {
		flex: 5;
	}

	.icon-hidden-show {
		position: absolute;
		right: 15px;
	}
}

.nut-dialog-form-item-z-yzm {
	position: relative;

	.btn {
		position: absolute;
		right: 0;
		top: 25px;
	}
}

.index-container {
	display: flex;
	flex-direction: column;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;

	.flex-container {
		flex: 1;
		padding: 0 25px;

		.flex-item {
			background-color: #fff;
			margin-top: 15px;
			border-radius: 15px;
		}

		.flex-item:nth-child(n + 2) {
			margin-top: 15px;
		}

		.flex-item:last-child {
			margin-bottom: 20px;
		}

		.flex-item1 {
			background-color: #fff;
			margin-top: 15px;
			border-radius: 15px;
		}

		.flex-item1:nth-child(n + 2) {
			margin-top: 15px;
		}

		.flex-item1:last-child {
			margin-bottom: 300px;
		}

		.custom-loading {
			display: inline-flex;
			align-items: flex-end;
			gap: 5px;
			min-height: 45px;
		}

		.custom-loading em {
			background: #5232b7;
			border-radius: 6px;
			display: inline-block;
			height: 100%;
			width: 10px;
			animation: animHeart 2s linear infinite;
		}

		@keyframes animHeart {
			0%,
			100% {
				height: 15px;
				background: #5232b7;
			}

			50% {
				height: 45px;
				background: #999;
			}
		}

		.custom-loading em:nth-child(2) {
			animation-delay: 0.2s;
		}

		.custom-loading em:nth-child(3) {
			animation-delay: 0.4s;
		}

		.custom-loading em:nth-child(4) {
			animation-delay: 0.6s;
		}

		.custom-loading em:nth-child(5) {
			animation-delay: 0.8s;
		}
	}
}
</style>
